package com.dsr.config;

import cn.hutool.core.date.DateTime;
import com.dsr.dao.*;
import com.dsr.entity.Address;
import com.dsr.entity.Flower;
import com.dsr.entity.Orders;
import com.dsr.entity.User;
import com.dsr.util.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

//@Configuration      //1.主要用于标记配置类，兼备Component的效果。
//@EnableScheduling   // 2.开启定时任务
public class StaticScheduleTask {
    @Autowired
    private OrdersDao ordersDao;
    @Autowired
    private FlowerDao flowerDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AddressDao addressDao;
    @Autowired
    private IdWorker idWorker;

    //3.添加定时任务
    @Scheduled(cron = "0 0/1 * * * ?")
    private void configureTasks() throws InterruptedException {
        Random random = new Random();
        List<User> users = userDao.selectAll();
        List<Flower> flowers = flowerDao.selectAll();
        List<Address> addresses = addressDao.selectAll();
        List<Orders> ordersList =new ArrayList<>();
        for (int i = 1; i <=144; i++) {
            int mouth=i%12+1;
            if(mouth>9){
                continue;
            }
            Thread.sleep(10);
            int day =random.nextInt(28)+1;
            int index =random.nextInt(flowers.size());
            int userIndex=random.nextInt(users.size());
            int addressindex=random.nextInt(addresses.size());
            User user=users.get(userIndex);
            Address address=addresses.get(addressindex);
            Flower flower=flowers.get(index);
            DateTime time = DateTime.of("2020-" + mouth + "-" + day+" 08:00:00", "yyyy-MM-dd HH:mm:ss");
            Orders orders = new Orders();
            orders.setUserId(user.getId());
            orders.setId(idWorker.nextId()+"");
            orders.setDel(0);
            orders.setUpdateDate(time);
            orders.setCreateDate(time);
            orders.setAddress(address.getAddress());
            orders.setAddressInfo(address.getAddressInfo());
            orders.setState(1);
            orders.setFlowerId(flower.getId());
            orders.setUserName(address.getUserName());
            orders.setPrice(flower.getPrice());
            orders.setNumber(userIndex);
            orders.setUserIphone(address.getUserIphone());
            ordersList.add(orders);
            System.err.println("执行静态定时任务时间: " + LocalDateTime.now());
        }
        ordersDao.insertOrdersList(ordersList);

    }
}